
import {useStore} from "@/stores";
import { handleMenus,} from "@/utils/SystemUtil";
import {getAuthUserInfo, loadAuthUserAsset, userToken} from "@/apis";
import MainLayout from "@/views/layouts/MainTopLayout.vue";
function updateUserAccessToken(accessToken: any): void {
    localStorage.setItem("user-token", accessToken)
}

const loadUserAssets = async (home: string) => {
    const retMenus: any = [];
    const store = useStore();
    const assets = await loadAuthUserAsset();

    if (assets.data) {
        handleMenus(retMenus, assets.data.menus);
        store.updateUserAssets(assets.data);
        store.buildRouteMenus(MainLayout, retMenus, home);
    }
}

export async function executeLoginSuccess(userData: any, home: string) {
    const store = useStore();
    updateUserAccessToken(userData.cred.accessToken);
    // 保存登录返回的用户信息
    store.setUserData(userData);
    await loadUserAssets(home);
}

// 登录成功
export async function executeLoginByCode(code: string, home: string) {
    if (code) {
        const result = await userToken(code);
        if (result && result.code === 0) {
            await executeLoginSuccess(result.data, home);
            return true;
        }
    }
    return false;
}

export async function getUserData() {
    const token: any = localStorage.getItem("user-token");
    if (token) {
        const result = await getAuthUserInfo(token);
        if (result && result.data) {
            return result.data;
        } else {
            localStorage.removeItem("user-token")
        }
    }

    return undefined;
}
